package com.fintech.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.dragon.app.commons.utils.FileDragonUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;

/**
 * 配置文件加载类
 * 
 * @author tux
 *
 */
@Component
public class PropertiesUtils {
	/**
	 * 接口开关状态关闭--OFF，其它情况都可认为是打开
	 */
	private static final String SWITCH_OFF = "OFF";

	private static String configPropertiesPath;
	
	
	public  String getConfigPropertiesPath() {
		return configPropertiesPath;
	}
	
	@Value("${config.properties.path}")
	public  void setConfigPropertiesPath(String configPropertiesPath) {
		PropertiesUtils.configPropertiesPath = configPropertiesPath;
	}
	
	/**
	 * 读取配置文件
	 * 
	 * @param filePath
	 * @return
	 */
	public static Properties load(String filePath) {
		Properties properties = new Properties();
		InputStream inputStream = null;
		try {
			inputStream = PropertiesUtils.class.getResourceAsStream(filePath);
			properties.load(inputStream);
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("加载配置文件出现异常->1; filePath = " + filePath, e);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("加载配置文件出现异常->2; filePath = " + filePath, e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception e) {
					MarvelsLogUtil.getInstance().error("关闭流出现异常", e);
				}
			}
		}
		return properties;
	}

	/**
	 * 获取配置文件具体数据
	 * 
	 * @param key
	 * @param filePath
	 *            文件相对路径，前面要带/
	 * @return
	 */
	public static String getString(String key, String filePath) {
		String value = ServerProperties.getValue(configPropertiesPath, filePath, key);
		MarvelsLogUtil.getInstance().info(filePath + " 配置文件键值对：[" + key + "->" + value + "]");
		return value;
	}

	public static String getString(String key) {
		return getString(key, "deploy.properties");
	}

	/**
	 * 获取开关相关配置
	 * 
	 * @param key
	 * @return
	 */
	public static String getSwitchString(String key) {
		return getString(key, "switch.properties");
	}

	/**
	 * 判断接口开关是否关闭<BR>
	 * 非OFF状态的都认为是打开<BR>
	 * 
	 * @param key
	 * @return
	 */
	public static boolean isTurnOffForSwitch(String key) {
		// 开关关闭
		if (SWITCH_OFF.equalsIgnoreCase(getSwitchString(key))) {
			MarvelsLogUtil.getInstance().info("开关关闭，不用调用第三方");
			return true;
		}
		return false;
	}

	/**
	 * 获取带有规则的前缀 /yyyy/xx/xx
	 */
	public static String getPathPrefix() {
		Calendar calendar = Calendar.getInstance();
		int day = calendar.get(Calendar.DATE);
		int month = calendar.get(Calendar.MONTH) + 1;
		int year = calendar.get(Calendar.YEAR);
		StringBuffer prefix = new StringBuffer();
		prefix.append("/").append(year).append("/").append(month).append("/").append(day);
		return prefix.toString();
	}

}
